import mongoose from "mongoose";
import fuzzySearch from "mongoose-fuzzy-searching";

// 添加新的评分统计和技术指标字段
const scoreStatsSchema = new mongoose.Schema(
  {
    // 总体评分
    overallScore: { type: Number, default: 0 },

    // 各维度评分
    technicalScore: { type: Number, default: 0 },
    contentScore: { type: Number, default: 0 },
    communityScore: { type: Number, default: 0 },

    // 评分可靠度指标 (0-1)
    reliability: { type: Number, default: 0 },

    // 上次评分更新时间
    lastUpdated: { type: Date, default: Date.now },
  },
  { _id: false }
);

const downloadStatsSchema = new mongoose.Schema(
  {
    // 总下载尝试次数
    attempts: { type: Number, default: 0 },

    // 成功完成的下载次数
    successful: { type: Number, default: 0 },

    // 下载成功率
    successRate: { type: Number, default: 0 },

    // 平均下载速度 (KB/s)
    avgSpeed: { type: Number, default: 0 },

    // 最近30天的统计
    last30Days: {
      attempts: { type: Number, default: 0 },
      successful: { type: Number, default: 0 },
      successRate: { type: Number, default: 0 },
    },
  },
  { _id: false }
);

const communityStatsSchema = new mongoose.Schema(
  {
    // 平均响应时间 (小时)
    avgResponseTime: { type: Number, default: 48 },

    // 讨论数量
    discussions: { type: Number, default: 0 },

    // 更新次数
    updates: { type: Number, default: 0 },

    // 发布以来的天数
    age: { type: Number, default: 0 },
  },
  { _id: false }
);

const schema = new mongoose.Schema({
  infoHash: String,
  binary: String,
  poster: String,
  uploadedBy: mongoose.Schema.ObjectId,
  name: String,
  description: String,
  type: String,
  source: String,
  image: String,
  downloads: Number,
  anonymous: Boolean,
  size: Number,
  files: Array,
  created: Number,
  upvotes: Array,
  downvotes: Array,
  freeleech: Boolean,
  tags: Array,
  group: mongoose.Schema.ObjectId,
  confidenceScore: Number,
  mediaInfo: String,

  // 新增字段
  scoreStats: {
    type: scoreStatsSchema,
    default: () => ({}),
  },

  downloadStats: {
    type: downloadStatsSchema,
    default: () => ({}),
  },

  communityStats: {
    type: communityStatsSchema,
    default: () => ({}),
  },

  lastScoringUpdate: {
    type: Date,
    default: null,
  },
});

schema.plugin(fuzzySearch, { fields: ["name"] });

// 创建文本索引
schema.index({ name: "text", description: "text" });

// 自动更新评分的间隔时间 (毫秒)
const SCORE_UPDATE_INTERVAL = 6 * 60 * 60 * 1000; // 6小时

// 每次下载时更新统计
schema.methods.recordDownload = async function (successful = true, speed = 0) {
  this.downloads += 1;
  this.downloadStats.attempts += 1;

  if (successful) {
    this.downloadStats.successful += 1;
  }

  // 更新成功率
  this.downloadStats.successRate =
    this.downloadStats.successful / this.downloadStats.attempts;

  // 更新平均速度
  if (speed > 0) {
    const totalSpeed =
      this.downloadStats.avgSpeed * (this.downloadStats.successful - 1) + speed;
    this.downloadStats.avgSpeed = totalSpeed / this.downloadStats.successful;
  }

  // 如果评分过期，触发更新
  if (
    !this.lastScoringUpdate ||
    Date.now() - this.lastScoringUpdate.getTime() > SCORE_UPDATE_INTERVAL
  ) {
    await this.updateScoreStats();
  }

  return this.save();
};

// 更新评分统计
schema.methods.updateScoreStats = async function () {
  try {
    const { calculateTorrentScore } = require("../utils/torrentScoring");

    this.lastScoringUpdate = new Date();

    // 计算种子发布至今的天数
    const createdDate =
      typeof this.created === "number" ? this.created : this.created.getTime();
    const ageInDays = Math.floor(
      (Date.now() - createdDate) / (24 * 60 * 60 * 1000)
    );
    this.communityStats.age = ageInDays > 0 ? ageInDays : 0;

    // 正确导入Rating和Comment模型
    const Rating = require("../models/rating").default;
    const Comment = require("../schema/comment").default;

    // 获取评分
    const ratings = await Rating.find({ torrentId: this.infoHash });
    const avgRating =
      ratings.length > 0
        ? ratings.reduce((sum, rating) => sum + rating.score, 0) /
          ratings.length
        : 0;

    // 获取评论
    const comments = await Comment.find({
      parentId: this._id,
      type: "torrent",
    }).sort({ created: -1 });

    // 组装评分所需数据
    const technicalData = {
      successRate: this.downloadStats.successRate || 0,
      seeders: this.seeders || 0,
    };

    const ratingData = {
      avgScore: avgRating,
      count: ratings.length,
    };

    const communityData = {
      responseTime: this.communityStats.avgResponseTime || 48,
      discussions: comments.length,
      updates: this.communityStats.updates || 0,
      age: this.communityStats.age || 0,
    };

    // 计算评分
    const scoreResult = calculateTorrentScore({
      stats: technicalData,
      ratings: ratingData,
      communityData,
    });

    // 更新评分数据
    this.scoreStats = {
      overallScore: scoreResult.finalScore,
      technicalScore: scoreResult.technicalScore,
      contentScore: scoreResult.contentScore,
      communityScore: scoreResult.communityScore,
      reliability: scoreResult.reliability,
      lastUpdated: new Date(),
    };

    return this.save();
  } catch (error) {
    console.error("Error updating score stats:", error);
    throw error;
  }
};

export default mongoose.model("torrent", schema);
